package com.ct.gd.passport.view;

import java.util.ArrayList;
import java.util.List;

import android.view.*;
import org.apache.commons.lang3.StringUtils;

import android.app.Activity;
import android.app.ActivityManager;
import android.app.AlertDialog;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.util.Pair;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.GridView;
import android.widget.TextView;

import com.ct.gd.passport.R;
import com.ct.gd.passport.common.BaseActivity;
import com.ct.gd.passport.common.connect.CtServer;
import com.ct.gd.passport.common.constants.Protocol;
import com.ct.gd.passport.common.constants.UmengVar;
import com.ct.gd.passport.util.TelephonyState;
import com.ct.gd.passport.view.consult.ConsultActivity;
import com.ct.gd.passport.view.passport.PassportHelperActivity;
import com.ct.gd.passport.view.policy.PolicyActivity;
import com.umeng.analytics.MobclickAgent;
import com.umeng.update.UmengUpdateAgent;
import com.up91.common.android.connect.NetUtil;
import com.up91.common.android.connect.Params;
import com.up91.common.android.view.adapter.SimpleListAdapter;

public class MainActivity extends BaseActivity implements OnItemClickListener {
	private List<Pair<Integer, Integer>> mItemInfos = new ArrayList<Pair<Integer, Integer>>();
	private GridView mGVEntries;

	protected AlertDialog shutdownDlg = null; // 退出

	@Override
	protected void onBaseCreate(Bundle savedInstanceState) {
		setContentView(R.layout.main);
	}

	@Override
	protected void initViews() {
		mGVEntries = (GridView) findViewById(R.id.gv_home_entries);

		mItemInfos.add(new Pair<Integer, Integer>(R.drawable.ic_passport,
				R.string.main_entry_passport));
		mItemInfos.add(new Pair<Integer, Integer>(R.drawable.ic_policy,
				R.string.main_entry_policy));
		mItemInfos.add(new Pair<Integer, Integer>(R.drawable.ic_consult,
				R.string.main_entry_advice));
		mItemInfos.add(new Pair<Integer, Integer>(R.drawable.ic_travel,
				R.string.main_entry_helper));
		mGVEntries.setAdapter(new GridViewAdapter(this, mItemInfos));
		mGVEntries.setOnItemClickListener(this);
		
		
		String version = getVersionName();
		if (StringUtils.isNotEmpty(version)){
		      TextView versionTv = (TextView)findViewById(R.id.tv_version);
		        versionTv.setText("V"+version);
            versionTv.setVisibility(View.GONE);
		}
	}

	 private String getVersionName() {
	           try {
                // 获取packagemanager的实例
                  PackageManager packageManager = getPackageManager();
                   // getPackageName()是你当前类的包名，0代表是获取版本信息
                   PackageInfo packInfo = packageManager.getPackageInfo(getPackageName(),0);
                   String version = packInfo.versionName;
                  return version;
            } catch (NameNotFoundException e) {
                e.printStackTrace();
            }
	         return null;
	   }
	 
	@Override
	protected void onAfterCreate(Bundle savedInstanceStat) {
		UmengUpdateAgent.setUpdateOnlyWifi(false);
		UmengUpdateAgent.update(this);
		new SendPhoneTask().execute();
		super.onAfterCreate(savedInstanceStat);
	}

	@Override
	protected void onResume() {
		super.onResume();
		checkNetwork();

	}

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu,menu);
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()){
            case R.id.share:
                //share
                String content = getResources().getString(R.string.share_content);
                Intent intent = new Intent();
                intent.putExtra("content", content).setClass(this, ShareActivity.class);
                startActivity(intent);
                break;
            case R.id.about:
                //about
                Intent aboutIntent = new Intent();
                aboutIntent.setClass(this, AboutActivity.class);
                startActivity(aboutIntent);
                break;
            case R.id.exit:
                //exit
                exitProgram();
                break;
        }
        return super.onOptionsItemSelected(item);
        //To change body of overridden methods use File | Settings | File Templates.
    }

    private static class GridViewAdapter extends
			SimpleListAdapter<Pair<Integer, Integer>> {
		public GridViewAdapter(Context context,
				List<Pair<Integer, Integer>> data) {
			super(context, data);
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			convertView = mInflater.inflate(R.layout.main_entries_item, parent,
					false);
			TextView tv = (TextView) convertView
					.findViewById(R.id.tv_main_entry_item);
			tv.setCompoundDrawablesWithIntrinsicBounds(0,
					getData().get(position).first, 0, 0);
			tv.setText(getData().get(position).second);
			return convertView;
		}
	}

	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position,
			long id) {
		Class<? extends Activity> target = null;
		switch (position) {
		case 0:
			MobclickAgent.onEvent(this, UmengVar.PASSPORT_INTRO);
			target = PassportHelperActivity.class;
			break;
		case 1:
			MobclickAgent.onEvent(this, UmengVar.POLICY_INTRO);
			target = PolicyActivity.class;
			break;
		case 2:
			MobclickAgent.onEvent(this, UmengVar.ADVICE_INTRO);
			target = ConsultActivity.class;
			break;
		case 3:
			MobclickAgent.onEvent(this, UmengVar.TRAVEL_INTRO);
			target = TravelAssistActivity.class;
			break;
		}
		if (null != target)
			startActivity(new Intent(this, target));
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		boolean flag = (keyCode == KeyEvent.KEYCODE_BACK);
		if (flag) {
			showExitDialog();
		}
		return flag;
	}

	/**
	 * 弹出退出程序的对话框
	 */
	public final void showExitDialog() {
		if (null == shutdownDlg) {
			shutdownDlg = new AlertDialog.Builder(this)
					.setTitle("确定要退出程序吗?")
					.setPositiveButton("确定",
							new DialogInterface.OnClickListener() {

								public void onClick(DialogInterface dialog,
										int which) {
									exitProgram();
								}
							})
					.setNegativeButton("取消",
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int which) {
									shutdownDlg.dismiss();
								}
							}).create();
		}
		shutdownDlg.show();
	}

	/**
	 * 退出程序
	 */
	public final void exitProgram() {
		/*
		 * Intent intent = new Intent(); intent.setAction(Constants.PACKAGE); //
		 * 说明动作 sendBroadcast(intent);// 该函数用于发送广播
		 */// 获得SDK的版本号
			// this.unregisterReceiver(screenReceiver);
		if (Build.VERSION.SDK_INT < 8) {// 如果SDK版本号小于8，即android2.2以下的系统
			((ActivityManager) getSystemService(Context.ACTIVITY_SERVICE))
					.restartPackage(getPackageName());
		} else {// 如果SDK版本号大于等于8，即android2.2以上的系统
			Intent startMain = new Intent(Intent.ACTION_MAIN);
			startMain.addCategory(Intent.CATEGORY_HOME);
			startMain.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
			startActivity(startMain);
			System.exit(0);
		}
	}

	private void checkNetwork() {
		// 若网络不可用，则提示退出
		if (NetUtil.isNetworkAvailable(MainActivity.this) == false) {
			AlertDialog.Builder netSettingDlg = new AlertDialog.Builder(
					MainActivity.this).setTitle("没有可用的网络").setMessage(
					"应用程序需要网络连接才能启动，是否对网络进行设置？");
			netSettingDlg
					.setPositiveButton("是",
							new DialogInterface.OnClickListener() {
								@Override
								public void onClick(DialogInterface dialog,
										int whichButton) {
									Intent mIntent = new Intent("/");
									ComponentName comp = new ComponentName(
											"com.android.settings",
											"com.android.settings.WirelessSettings");
									mIntent.setComponent(comp);
									mIntent.setAction("android.intent.action.VIEW");
									MainActivity.this.startActivity(mIntent);
								}
							})
					.setNeutralButton("关闭应用",
							new DialogInterface.OnClickListener() {
								@Override
								public void onClick(DialogInterface dialog,
										int whichButton) {
									exitProgram();
								}
							}).show();
		}
	}

	class SendPhoneTask extends AsyncTask<String, Void, String> {

		@Override
		protected String doInBackground(String... para) {
			String phoneNumber = TelephonyState.getInstance().getPhoneNumber();
			if (StringUtils.isBlank(phoneNumber) == false) {
				Params params = new Params();
				params.put(Protocol.Fields.IMEI, TelephonyState.getInstance()
						.getIMEI());
				params.put(Protocol.Fields.USER_PHONE, phoneNumber);
				try {
					CtServer.getServer().doGet(
							Protocol.Commands.COMMON_SEND_PHONE, params);
				} catch (Exception e) {
					e.printStackTrace();
				}

			}
			return null;
		}

	}

}